package com.zhang.web.filter;


import com.zhang.domain.User;
import com.zhang.service.impl.UserServiceImpl;
import com.zhang.utils.CookieUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLDecoder;

/*@WebFilter("/*")*/
public class BLoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    @Override
    public void destroy() {

    }


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("B.7天免费登录过滤器..");
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse)servletResponse;
        String uri = req.getRequestURI();

        //1.login.html  + /login动态资源  放行
        if(uri.contains("login.html") || uri.contains("/login") || uri.contains("/checkCodeServlet") || uri.contains("/jquery-3.3.1.js")){
            filterChain.doFilter(req,resp);
            return;
        }

        //2.session 放行
        HttpSession session = req.getSession();
        User user = (User)session.getAttribute("user");
        if(user != null){
            filterChain.doFilter(req,resp);
            return;
        }

        //3.cookie 放行
        Cookie cookie = CookieUtils.getCookie("remember", req);
        if(cookie != null){
            String value = URLDecoder.decode(cookie.getValue(),"UTF-8") ;
            String[] usernameAndPass = value.split("#");
            String username = usernameAndPass[0];
            String password = usernameAndPass[1];

            //判断用户密码
            UserServiceImpl userService = new UserServiceImpl();
            User user1 = userService.login(username, password);
            if (user1 != null){
                //正确
                session.setAttribute("user",user1);
                filterChain.doFilter(req,resp);
            }else{
                //错误
                resp.sendRedirect("/comPro/login.html");
            }
        }else {
            resp.sendRedirect("/comPro/login.html");
        }

    }


}




















